﻿using EnterpriseWebsiteApi.ActionFilters;
using EnterpriseWebsiteApi.Dto.AboutUs;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace EnterpriseWebsiteApi.Controllers.Admin
{
    [Route("api/admin/[controller]/[action]")]
    [ApiController]
    [TypeFilter(typeof(JwtAuthorizeFilter))]
    public class UploadController : ControllerBase
    {
        /// <summary>
        /// 图片上传
        /// </summary>
        /// <param name="mediaFile"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<WangEditorUploadDto>> Image(IFormFile mediaFile)
        {
            try
            {
                string directoryName = "imageUpload";
                WangEditorUploadDataDto editorUploadData = new WangEditorUploadDataDto();

                if (mediaFile == null)
                {
                    return Ok(new WangEditorUploadDto() { errno = 1, message = "未有上传文件" });
                }
                if (mediaFile.Length > 2 * 1024 * 1024)
                {
                    return Ok(new WangEditorUploadDto() { errno = 1, message = "上传的图片不能大于2mb" });
                }

                string mediaType = Path.GetExtension(mediaFile.FileName).ToLower();
                string fileName = $"{Guid.NewGuid()}{mediaType}";
                string folderPath = Path.Combine("wwwroot", directoryName);
                string filePath = Path.Combine("wwwroot", directoryName, fileName);

                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                }

                using (FileStream stream = new FileStream(filePath, FileMode.Create))
                {
                    await mediaFile.CopyToAsync(stream);
                }

                string baseUrl = $"{Request.Scheme}://{Request.Host}{Request.PathBase}";
                string mediaUrl = $"/{directoryName}/{fileName}";
                editorUploadData.url = $"{baseUrl}{mediaUrl}";
                return Ok(new WangEditorUploadDto() { errno = 0, data = editorUploadData });
            }
            catch (Exception ex) 
            {
                return Ok(new WangEditorUploadDto() { errno = 1, message = ex.ToString() });
            }
        }

    }
}
